package sel.me.spring.boot245.web.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import sel.me.spring.boot245.web.domain.login.LoginUserDto;
import sel.me.spring.boot245.web.entity.User;
import sel.me.spring.boot245.web.service.UserService;


/**
 * @author shenenlu
 * @date 2021-7-28 19:18
 */
@Component
public class SelfUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 查询用户信息
     *
     * @Author youcong
     * @Param username  用户名
     * @Return UserDetails SpringSecurity用户信息
     */
    @Override
    public LoginUserDto loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> wrapper = new QueryWrapper<>();


        //邮箱正则表达式
        String expr = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$";

        //是否为邮箱
        if (username.matches(expr)) {
            wrapper.eq("user_email", username);
        } else {
            wrapper.eq("user_login", username);
        }

        // 查询用户信息
        User sysUserEntity = userService.selectOne(wrapper);
        if (sysUserEntity != null) {
            // 组装参数
            LoginUserDto selfUserEntity = new LoginUserDto();
            BeanUtils.copyProperties(sysUserEntity, selfUserEntity);
            return selfUserEntity;
        }
        return null;
    }
}
